package com.situ.gym.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.situ.gym.pojo.User;
import com.situ.gym.pojo.User;
import com.situ.gym.pojo.User;
import com.situ.gym.pojo.dto.UserPasswordDTO;
import com.situ.gym.pojo.query.UserQuery;
import com.situ.gym.service.IUserService;
import com.situ.gym.util.JwtUtil;
import com.situ.gym.util.Result;
import com.situ.gym.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2025-08-22
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;


    @GetMapping("/selectAssignRole/{userId}")
    public Result selectAssignRole(@PathVariable Integer userId) {
        //List<Role> roleList;
        //List<Long> assignedRoleIdList;
        Map<String, Object> map =  userService.selectAssignRole(userId);
        return Result.ok(map);
    }

    @PostMapping("/assignRole")
    public Result assignRole(Long userId, Long[] roleIds) {
        userService.assignRole(userId, roleIds);
        return Result.ok("分配成功");
    }

    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody UserPasswordDTO userPasswordDTO,
                                @RequestHeader(name = "Authorization")String token) {
        //Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = userService.getById(id);
        //先判断就密码是否正确
        if (!user.getPassword().equalsIgnoreCase(userPasswordDTO.getOldPassword())) {
            return Result.error("旧密码错误");
        }

        User userUpdate = new User();
        userUpdate.setId(user.getId());
        userUpdate.setPassword(userPasswordDTO.getNewPassword());
        userService.updateById(userUpdate);
        return Result.ok("更新成功");

    }


    @GetMapping("/userInfo")
    public Result userInfo(@RequestHeader(name = "Authorization")String token) {
        //Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        //Long.valueOf(map.get("id").toString())
        Integer id = (Integer) tokenMap.get("id");
        //User user = userService.getById(id);
        //user.setPassword(null);
        //除了有User，还有这个用户的所有权限信息
        Map<String, Object> map = userService.selectUserPermissionInfoById(id);
        return Result.ok(map);
    }


    @PostMapping("/login")
    public Result userlogin(@RequestBody User user) {
        //名字是唯一的
        User loginUser = userService.selectByName(user.getName());
        if (loginUser == null) {
            return Result.error("用户名错误");
        }

        //判断密码是否正确
        if (!user.getPassword().equals(loginUser.getPassword())) {
            return Result.error("密码错误");
        }
        if (loginUser.getStatus() == 0) {
            return Result.error("该用户已经被禁用");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginUser.getId());
        map.put("name", loginUser.getName());
        map.put("role", "user");
        String token = JwtUtil.createToken(map);
        return Result.ok("登录成功", token);
    }

    @GetMapping("/selectAll")
    public Result<List<User>> selectAll() {
        List<User> list = userService.list();
        return Result.ok(list);
    }

    //Restful    GET(查找)、POST(添加)、DELETE(删除)、PUT(修改)
    //@RequestMapping("/list")
    //@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    //@RequestMapping(value = "/list", method = RequestMethod.GET)
    @GetMapping("/list")
    public Result<IPage<User>> list(UserQuery userQuery) {
        System.out.println("UserController.list");
        IPage<User> page = userService.list(userQuery);
        return Result.ok(page);
    }

    // /deleteById?id=1
    // /deleteById/1
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.ok("删除成功");
    }

    // /deleteAll/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        //userService.removeBatchByIds(Arrays.asList(ids));
        userService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    /*@PostMapping("/add")
    public Result add(User user) {
        System.out.println(user);
        return Result.ok();
    }*/

    // @RequestBody : 封装前台传递过来的JSON格式数据
    // @ResponseBody : 将数据转换为JSON格式返回
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        // 1. 判断用户名是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", user.getName());
        User existingUser = userService.getOne(queryWrapper);

        if (existingUser != null) {
            return Result.error("用户名已存在，请换一个");
        }

        // 2. 保存用户
        userService.save(user);
        return Result.ok("添加成功");
    }


    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        System.out.println(user);
        //userService.saveOrUpdate(user);
        userService.updateById(user);
        return Result.ok("更新成功");
    }

    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        userService.updateById(user);
        return Result.ok("修改成功");
    }
}

